﻿using Newtonsoft.Json.Linq;
using StockDataBase;
using StockDataBase.DataOperation;
using StockDataBase.models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using 股票数据;

namespace Download
{
    class DownloadFile
    {
        int code = 897;
        string formate = "http://stock.finance.qq.com/hk/hklist/view/show.php?t=finreport&c=download&code={0:00000}&type={1}";
        ProgressBar bar;

        public DownloadFile(int start,ProgressBar bar)
        {
            code = start;
            this.bar = bar;

        }

        WebClient client = new WebClient();
        public void Down(int code)
        {
           
            string dir = @"data\" + string.Format("{0:00000}", code);
            Directory.CreateDirectory(dir);
            for (int i = 1; i <= 3; i++)
            {
                string url = string.Format(formate, code, i);
                client.DownloadFile(url, dir + @"\" + i + ".xls");
            }
        }
    }

    


    public class DownAllNews : DownBase
    {
        ProgressBar pb;
        ProgressBar pb2;
        public DownAllNews( ProgressBar pb,ProgressBar pb2)
        {
            this.pb = pb;
            this.pb2 = pb2;
        }

        public void StartDownThread()
        {
            pb2.Minimum =0;
            pb.Value = 0;
            pb2.Value = 0;

            new Thread(() => {
                //创建表
                Utils.DB_Client.CreateTable(typeof(NewsInfo));

                //先遍历基本信息数据库
                //NewsDataOp nop = new NewsDataOp();
                int idx = 0;
                var stocks = Utils.DB_Client.Select<StockInfo>();
                int count = stocks.Count;
                pb.Dispatcher.BeginInvoke(new Action(() =>
                {
                    pb2.Maximum = count;
                }));
                while (idx < count )
                {
                    //先判断 新闻表 里面有没有这个id了

                    string id = stocks[idx].stockId;
                    int pageCount = 1;

                    try
                    {
                        for (int i = 1; i <= pageCount; i++)
                        {
                            var url = "http://news2.gtimg.cn/lishinews.php?name=finance_news&symbol={0}&page={1}";
                            url = string.Format(url, id, i);
                            string content = this.DownString(url);
                            content = Utils.ConvertJs2Csharp(content);
                            content = content.Remove(0, "var finance_news=".Length);
                            try
                            {
                                JObject jo = JObject.Parse(content);

                                foreach (JObject item in jo["data"]["data"])
                                {
                                    //nop.InsertItem(item["uid"].ToString(), item["datetime"].ToString(), item["symbol"].ToString(), item["title"].ToString(), item["url"].ToString());
                                    var newsInfo = new NewsInfo()
                                    {
                                        uid = item["uid"].ToString(),
                                        datetime = item["datetime"].ToString(),
                                        symbol = item["symbol"].ToString(),
                                        title = item["title"].ToString(),
                                        url = item["url"].ToString(),
                                    };

                                    var res = Utils.DB_Client.Select<NewsInfo>(x => x.uid == newsInfo.uid);
                                    if (res.Count == 0)
                                    {
                                        Utils.DB_Client.Insert<NewsInfo>(newsInfo);
                                    }

                                }
                                pageCount = int.Parse(jo["data"]["total_page"].ToString());
                                pb.Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    pb.Minimum = 1;
                                    pb.Maximum = pageCount;
                                    pb.Value = i;
                                }));
                            }
                            catch (Exception)
                            {
                                StreamWriter sw = new StreamWriter("test.js");
                                sw.Write(content);
                                sw.Close();
                                throw;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                    pb.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        pb2.Value = idx++;
                    }));
                }
                pb.Dispatcher.BeginInvoke(new Action(() =>
                {
                    MessageBox.Show("下载完毕");
                }));

            }).Start();
            
        }


        public void AddNewsThread()
        {
            pb2.Minimum = 0;
            NewsDataOp nop = new NewsDataOp();

            var res = nop.ExcuteReader("select COUNT(*) as Count from  baseInfo");
            res.Read();
            pb2.Maximum = int.Parse(res["Count"].ToString());

            new Thread(() =>
            {
                //先遍历基本信息数据库
                int idx = 0;
                res = nop.ExcuteReader("select * from baseInfo ");
                while (res.Read())
                {
                    //下载第一页 如果第一页的数据不在数据库里面就插入相应的数据

                    string id = res["StockId"].ToString();
                    int pageCount = 1;
                    nop.Begin();

                    for (int i = 1; i <= pageCount; i++)
                    {
                        string content = this.DownString(string.Format("http://news2.gtimg.cn/lishinews.php?name=finance_news&symbol={0}&page={1}", id, i));
                        content = Utils.ConvertJs2Csharp(content);
                        content = content.Remove(0, "var finance_news=".Length);
                        try
                        {
                            JObject jo = JObject.Parse(content);
                            bool find_already_exist = false;
                            foreach (JObject item in jo["data"]["data"])
                            {
                                string uid = item["uid"].ToString();
                                //看看新闻数据库里面有没有这个
                                var reader = nop.ExcuteReader("select * from news where Uid='"+uid+"'");
                                if(reader .Read())
                                {
                                    find_already_exist = true;
                                    //Console.WriteLine("已存在" + uid);
                                }
                                else
                                {
                                    //找不到才插进去
                                    nop.InsertItem(uid, item["datetime"].ToString(), item["symbol"].ToString(), item["title"].ToString(), item["url"].ToString());
                                    Console.WriteLine("新新闻 " + item["title"].ToString());
                                }

                            }
                            Console.WriteLine("stockid = " + id + " page " + i + "...........");
                            pageCount = int.Parse(jo["data"]["total_page"].ToString());
                            //一页循环下来如果发现了有存在数据库里面的条目就不在下载下一页
                            if(find_already_exist)
                            {
                                break;
                            }
                        }
                        catch (Exception)
                        {
                            StreamWriter sw = new StreamWriter("test.js");
                            sw.Write(content);
                            sw.Close();
                            throw;
                        }
                    }
                    nop.End();

                    pb.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        pb2.Value = idx++;
                    }));
                }

            }).Start();

        }
    }





}
